package com.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.dao.MessageDAO;
import com.model.Message;
import com.model.Users;
import com.opensymphony.xwork2.ModelDriven;
import com.page.Pagination;
import com.page.PaginationImpl;

public class MessageAction implements ModelDriven<Message>{

	private Message message;
	MessageDAO messageDAO=new MessageDAO();
	HttpServletRequest request=ServletActionContext.getRequest();

	public String add() {
		messageDAO.insert(message);
		return "success";
	}
	public String delete() {
	   	String sid=request.getParameter("id");
	   	messageDAO.delete(Integer.parseInt(sid));
		return "success";
	}

	public String edit() {
		String sid = (String) request.getParameter("id");
		Message message = messageDAO.get(Integer.parseInt(sid));
		request.setAttribute("message", message);
		return "success";
	}
	public String update() {
		messageDAO.update(message);
		return "success";
	}
	public String show() {
		HttpSession session=request.getSession();
		Pagination page= new PaginationImpl();
		page.setPageSize(3);
		String function=request.getParameter("function");
		String pageNumber=request.getParameter("pageNumber");
		if(pageNumber==null) page.setPageNumber(1);
		else page.setPageNumber(Integer.parseInt(pageNumber));
		if(function==null) {
			function=(String)session.getAttribute("function");
			if(function==null)function="all";
		}
		session.setAttribute("function",function);
		if("my".equals(function)){
			Users u=(Users)request.getSession().getAttribute("loginUser");
			page = messageDAO.getAll(page,u.getUsername());
		}else page = messageDAO.getAll(page);
		request.setAttribute("mslist", page);
		return "success";
	}

	public Message getMessage() {
		return message;
	}


	public void setMessage(Message message) {
		this.message = message;
	}


	@Override
	public Message getModel() {
		message=new Message();
		return this.getMessage();
	}

}
